// src/composables/useFileUpload.js
import { ref, reactive } from 'vue'

/**
 * 文件上传组合式函数
 * @param {Object} options - 配置项
 * @returns {Object} 文件状态与操作方法
 */
export function useFileUpload(options = {}) {
  const {
    maxFiles = 5,
    maxSize = 5 * 1024 * 1024, // 5MB
    accept = 'image/*',
  } = options

  const files = ref([]) // File 对象数组
  const previews = ref([]) // 预览 URL 数组
  const uploadStatus = reactive({
    uploading: false,
    progress: 0,
    success: false,
    error: null,
  })

  // 添加文件
  const addFiles = (newFiles) => {
    if (files.value.length + newFiles.length > maxFiles) {
      uploadStatus.error = `最多只能上传 ${maxFiles} 个文件`
      return
    }

    const validFiles = []
    for (const file of newFiles) {
      if (file.size > maxSize) {
        uploadStatus.error = `${file.name} 超过 ${maxSize / 1024 / 1024}MB`
        continue
      }
      validFiles.push(file)
    }

    files.value.push(...validFiles)

    // 生成预览 URL
    const newPreviews = validFiles.map((file) => URL.createObjectURL(file))
    previews.value.push(...newPreviews)
  }

  // 删除文件
  const removeFile = (index) => {
    files.value.splice(index, 1)
    const url = previews.value.splice(index, 1)[0]
    URL.revokeObjectURL(url) // 释放内存
  }

  // 模拟上传（实际项目中替换为 axios/fetch）
  const upload = async () => {
    if (files.value.length === 0) return

    uploadStatus.uploading = true
    uploadStatus.progress = 0
    uploadStatus.success = false
    uploadStatus.error = null

    try {
      // 模拟上传进度
      for (let i = 0; i <= 100; i += 10) {
        await new Promise((resolve) => setTimeout(resolve, 100))
        uploadStatus.progress = i
      }

      uploadStatus.success = true
      console.log('上传成功！文件:', files.value)
    } catch (err) {
      uploadStatus.error = '上传失败，请重试'
    } finally {
      uploadStatus.uploading = false
    }
  }

  // 重置
  const reset = () => {
    files.value.forEach((file, i) => {
      URL.revokeObjectURL(previews.value[i])
    })
    files.value = []
    previews.value = []
    uploadStatus.uploading = false
    uploadStatus.progress = 0
    uploadStatus.success = false
    uploadStatus.error = null
  }

  return {
    files,
    previews,
    uploadStatus,
    addFiles,
    removeFile,
    upload,
    reset,
    accept,
    maxFiles,
    maxSize,
  }
}
